import pygame, sys, math, random

pygame.init()

from Block import Block
from Player import Player
from HardBlock import HardBlock
from Enemy import Enemy
from PlayerGun import PlayerGun
from Background import Background
from Bullet import Bullet
from LevelBlock import LevelBlock
from InvisibleBlock import InvisibleBlock

clock = pygame.time.Clock()

width = 1000
height = 600
size = width, height

blocksize = [50,50]
playersize = [40,40]
killCount = 0

screen = pygame.display.set_mode(size)
bgColor = r,g,b = 0,0,0

guns = pygame.sprite.Group()
blocks = pygame.sprite.Group()
hardBlocks = pygame.sprite.Group()
enemies = pygame.sprite.Group()
backgrounds = pygame.sprite.Group()
players = pygame.sprite.Group()
all = pygame.sprite.OrderedUpdates()
bullets = pygame.sprite.Group()
levelBlocks = pygame.sprite.Group()
InvisibleBlocks = pygame.sprite.Group()

PlayerGun.containers = (all, guns)
Player.containers = (all, players)
Block.containers = (all, blocks)
HardBlock.containers = (all, hardBlocks, blocks)
Enemy.containers = (all, enemies)
Background.containers = (all, blocks)
Bullet.containers = (all, bullets)
LevelBlock.containers = (all, levelBlocks, blocks)
InvisibleBlock.containers = (all, InvisibleBlocks, blocks)

bg = Background("rsc/bg/mainbg.png", size)

def loadLevel(level):
    f = open(level+".lvl", 'r')
    lines = f.readlines()
    f.close()
    
    newlines = []
    
    for line in lines:
        newline = ""
        for c in line:
            if c != "\n":
                newline += c
        newlines += [newline]
        
    #for line in newlines:
        #print line
    
    for y, line in enumerate(newlines):
        for x, c in enumerate(line):
            if c == "#":
                HardBlock("rsc/blocks/black.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == "p":
                Block("rsc/blocks/purple.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == "b":
                Block("rsc/blocks/blue.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == "g":
                LevelBlock("rsc/blocks/goal.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2-20],
                      blocksize)
            elif c == "i":
                InvisibleBlock("rsc/blocks/invisible.png",
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2-20],
                      blocksize)
    
    f = open(level+".tng", 'r')
    lines = f.readlines()
    f.close()
    
    newlines = []
    
    for line in lines:
        newline = ""
        for c in line:
            if c != "\n":
                newline += c
        newlines += [newline]
    
    for y, line in enumerate(newlines):
        for x, c in enumerate(line):
            if c == "@":
                player = Player([(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
                     playersize,
                     size)
            elif c == "e":
                Enemy("rsc/enemy/spikeBall.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2])
    PlayerGun(player.rect.center)                  
    for each in all.sprites():
        each.fixLocation(player.offsetx, player.offsety)
    killCount = 0
def loadNextLevel(level):    
    for i in all.sprites():
        i.kill()
    bg = Background("rsc/bg/mainbg.png", size)
    screen.blit(bg.image, bg.rect)
    loadLevel(levels[level])
    player1Gun = guns.sprites()[0]
    killCount = 0
     
    

levels = ["rsc/levels/level1",
          "rsc/levels/level2",
          "rsc/levels/level3"]
level = 0
loadLevel(levels[level])
player1 = players.sprites()[0]
player1Gun = guns.sprites()[0]


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:

                level = 0
                for each in all.sprites():
                    each.kill()
                bg = Background("rsc/bg/mainbg.png", size)
                screen.blit(bg.image, bg.rect)
                loadLevel(levels[level])
                player1 = players.sprites()[0]
                player1Gun = guns.sprites()[0]

            if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
                player1.direction("right")
            if event.key == pygame.K_a or event.key == pygame.K_LEFT:
                player1.direction("left")
            if event.key == pygame.K_w or event.key == pygame.K_UP:
                player1.direction("up")
            if event.key == pygame.K_s or event.key == pygame.K_DOWN:
                player1.direction("down")
            if event.key == pygame.K_SPACE:
                player1.jump()

        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                if player1Gun.angle <= 90 and player1Gun.angle >= -90:
                    Bullet([player1Gun.rect.center[0] + 37.34*(math.cos((player1Gun.angle*math.pi/180)+.13439)), player1Gun.rect.center[1] - 37.34*(math.sin((player1Gun.angle*math.pi/180)+.13439))], player1Gun.angle)

                elif player1Gun.angle > 90 and player1Gun.angle <= 180:
                    Bullet([player1Gun.rect.center[0] + 37.34*(math.cos((player1Gun.angle*math.pi/180)-.13439)), player1Gun.rect.center[1] - 37.34*(math.sin((player1Gun.angle*math.pi/180)-.13439))], player1Gun.angle)

                elif player1Gun.angle < -90 and player1Gun.angle > -180:
                    Bullet([player1Gun.rect.center[0] + 37.34*(math.cos((player1Gun.angle*math.pi/180)-.13439)), player1Gun.rect.center[1] - 37.34*(math.sin((player1Gun.angle*math.pi/180)-.13439))], player1Gun.angle)

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
                player1.direction("stop right")
            if event.key == pygame.K_a or event.key == pygame.K_LEFT:
                player1.direction("stop left")
            # if event.key == pygame.K_w or event.key == pygame.K_UP:
                # player1.direction("stop up")
            if event.key == pygame.K_s or event.key == pygame.K_DOWN:
                player1.direction("stop down")

                
    playersHitBlocks = pygame.sprite.groupcollide(players, hardBlocks, False, False)
    enemiesHitBlocks = pygame.sprite.groupcollide(enemies, hardBlocks, False, False)
    enemiesHitEnemies = pygame.sprite.groupcollide(enemies, enemies, False, False)
    bulletsHitEnemies = pygame.sprite.groupcollide(bullets, enemies, True, True)
    bulletsHitBlocks = pygame.sprite.groupcollide(bullets, hardBlocks, True, False)
    bulletsHitBlocks = pygame.sprite.groupcollide(bullets, levelBlocks, True, False)
    playerHitLB = pygame.sprite.groupcollide(players, levelBlocks, False, True)
    playerHitIB = pygame.sprite.groupcollide(players, InvisibleBlocks, True, False)
    enemiesHitPlayers = pygame.sprite.groupcollide(enemies, players, False, True)
    
    
    #print player1Gun.angle
    for bullet in bullets.sprites():
        if not bullet.living:
            bullet.kill()
            
    for player in playersHitBlocks:
        for block in playersHitBlocks[player]:
            player.collideBlock(block)
    
    for player in playerHitIB:
        for block in playerHitIB[player]:
            player.collideBlock(block)
            bg = Background("rsc/bg/gameover.png", size)
            pass
    
    for enemy in enemiesHitPlayers:
        for player in enemiesHitPlayers[enemy]:
            bg = Background("rsc/bg/gameover.png", size)
            pass
            
    for bullet in bulletsHitEnemies:
        for enemy in bulletsHitEnemies[bullet]:
            killCount += 1

    

            
    for enemy in enemiesHitBlocks:
        for block in enemiesHitBlocks[enemy]:
            enemy.collideBlock(block)
            
    for enemy in enemiesHitEnemies:
        for otherEnemy in enemiesHitEnemies[enemy]:
            enemy.collideBlock(otherEnemy)
    
    for player in playerHitLB:
        for block in playerHitLB[player]:
            if level < len(levels)-1:
                level += 1
            else:
                level = 0
            loadNextLevel(level)
            player1 = players.sprites()[0]
            player1Gun = guns.sprites()[0]

            

    all.update(size,
               player1.speedx, 
               player1.speedy, 
               player1.scrollingx, 
               player1.scrollingy,
               player1.realx,
               player1.realy,
               player1.x,
               player1.y,
               player1Gun.rect,
               player1Gun.angle,
               player1Gun.place,

               )

             
    scoreFont = pygame.font.Font(None, 48)
    scoreText = scoreFont.render("Score: " + str(killCount), 1, (200,0,0))
    scoreTextPos = scoreText.get_rect(centerx=50, centery=50)
    screen.blit(scoreText, scoreTextPos)
    dirty = all.draw(screen)
    pygame.display.update(dirty)
    pygame.display.flip()
    clock.tick(30)















